package com.yao.mall.controller;

import com.yao.mall.common.ErrorCode;
import com.yao.mall.common.Result;
import com.yao.mall.config.AliyunOSSConfig;
import com.yao.mall.config.BusinessException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author jiahua.yao
 * @version 1.0
 * @description 文件管理控制层（统一系统的需要处理的文件相关字段值）
 * @date 2024/3/19 17:02
 */
@RestController
@RequestMapping("/file")
@Slf4j
@Tag(name = "文件管理相关接口")
public class FileController {
    @PostMapping("/upload")
    @Operation(summary = "文件上传")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file){
        String fileStr = AliyunOSSConfig.OSSUploadFile(file);
        if (fileStr == null) {
            throw new BusinessException(ErrorCode.File_UPLOAD_ERROR,"上传失败");
        }
        return Result.success(fileStr);
    }

    @PostMapping("/uploadList")
    @Operation(summary = "多文件上传")
    public Result<List<String>> uploadFileList(@RequestParam("fileList") List<MultipartFile> fileList){
        List<String> stringList = fileList.stream().map(file -> {
            String fileStr = AliyunOSSConfig.OSSUploadFile(file);
            if (fileStr == null) {
                throw new BusinessException(ErrorCode.File_UPLOAD_ERROR, "上传失败");
            }
            return fileStr;
        }).toList();
        return Result.success(stringList);
    }

    /**
     * 文件删除
     * @param url 文件地址
     * @return boolean
     */
    @PostMapping("/delete")
    @Operation(summary = "文件删除")
    public Result<Boolean> deleteFile(@RequestParam String url){
        Boolean aBoolean = AliyunOSSConfig.OSSDeleteFile(url);
        return Result.success(aBoolean);
    }
}

